package com.example.administrator.demoa;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.tencent.smtt.sdk.WebView;

import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class NewsDetailActivity extends AppCompatActivity {
    private WebView news_web;
    private Button btn_send;
    private EditText edt_comment;
    private ImageView iv_like;
    private String newsId;
    private String newsJson;
    private boolean isLike = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);

        news_web = findViewById(R.id.news_web);
        btn_send = findViewById(R.id.btn_send);
        edt_comment = findViewById(R.id.edt_comment);
        iv_like = findViewById(R.id.iv_like);

        ClickBtnSend();
        ClickLike();

        String title = getIntent().getStringExtra("TITLE");
        String url = getIntent().getStringExtra("URL");
        newsId = getIntent().getStringExtra("NEWSID");
        newsJson = getIntent().getStringExtra("NEWSJSON");

        setTitle(title);
        news_web.loadUrl(url);

        //查询是否之前收藏过，有则显示
        queryAndIsShow();
    }

    private void ClickBtnSend() {
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //登录可评论，不然进入登录页面
                if(BmobUser.getCurrentUser(BmobUser.class) == null){
                    Intent intent = new Intent(NewsDetailActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }

                final String userId = BmobUser.getCurrentUser(BmobUser.class).getObjectId();

                String content = edt_comment.getText().toString().trim();
                if(content.length() == 0){
                    Toast.makeText(NewsDetailActivity.this, "请先评论",
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                BmobDate time = new BmobDate(new Date());

                //评论内容保存
                Comment comment = new Comment();
                comment.setContent(content);
                comment.setNewsId(newsId);
                comment.setUserId(userId);
                comment.setNewsJson(newsJson);
                comment.setTime(time);
                comment.save(new SaveListener<String>() {
                    @Override
                    public void done(String s, BmobException e) {
                        if(e == null){
                            Toast.makeText(NewsDetailActivity.this, "评论成功",
                                    Toast.LENGTH_SHORT).show();
                            edt_comment.setText("");
                        }
                    }
                });
            }
        });
    }

    private void ClickLike() {
        iv_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //登录可收藏，不然进入登录页面
                if(BmobUser.getCurrentUser(BmobUser.class) == null){
                    Intent intent = new Intent(NewsDetailActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }

                iv_like.setClickable(false);

                final String userId = BmobUser.getCurrentUser(BmobUser.class).getObjectId();

                //查询是否有此新闻的数据
                BmobQuery<Like> likeBmobQuery = new BmobQuery<>();
                likeBmobQuery.addWhereEqualTo("userId", userId);
                likeBmobQuery.addWhereEqualTo("newsId", newsId);
                likeBmobQuery.findObjects(new FindListener<Like>() {
                    @Override
                    public void done(List<Like> list, BmobException e) {
                        //设置iv_like五角星图标的setClickable()
                        //使其done的时候才可点击，减少用户提交数据的交互次数
                        iv_like.setClickable(true);
                        if(e == null){
                            if(list != null && list.size() > 0){
                                //有数据（更新收藏状态）
                                Like like = list.get(0);
                                like.setLike(!isLike);
                                like.update(new UpdateListener() {
                                    @Override
                                    public void done(BmobException e) {
                                        if(e == null) {
                                            isLike = !isLike;
                                            sendBroadcast(new Intent().setAction("LIKE_CHANGED"));
                                            if (isLike) {
                                                iv_like.setImageResource(R.drawable.redstar);
                                            } else {
                                                iv_like.setImageResource(R.drawable.blackstar);
                                            }
                                        }
                                    }
                                });
                            }else{
                                //若未有此新闻，添加
                                Like like = new Like();
                                like.setUserId(userId);
                                like.setNewsId(newsId);
                                like.setNewsJson(newsJson);
                                like.setLike(true);
                                like.save(new SaveListener<String>() {
                                    @Override
                                    public void done(String s, BmobException e) {
                                        if(e == null){
                                            isLike = !isLike;
                                            sendBroadcast(new Intent().setAction("LIKE_CHANGED"));
                                            if(isLike){
                                                iv_like.setImageResource(R.drawable.redstar);
                                            }else{
                                                iv_like.setImageResource(R.drawable.blackstar);
                                            }
                                        }
                                    }
                                });
                            }
                        }
                    }
                });
            }
        });
    }

    private void queryAndIsShow() {
        //如果无登录，不需要查询
        if(BmobUser.getCurrentUser(BmobUser.class) == null){
            return;
        }

        final BmobQuery<Like> likeBmobQuery = new BmobQuery<>();
        String userId = BmobUser.getCurrentUser(BmobUser.class).getObjectId();
        likeBmobQuery.addWhereEqualTo("userId", userId);
        likeBmobQuery.addWhereEqualTo("newsId", newsId);
        likeBmobQuery.addWhereEqualTo("isLike", true);
        likeBmobQuery.findObjects(new FindListener<Like>() {
            @Override
            public void done(List<Like> list, BmobException e) {
                if(list != null && list.size() > 0){
                    isLike = true;
                    iv_like.setImageResource(R.drawable.redstar);
                }
            }
        });
    }
}
